#include "IntLinkedList.h"


IntLinkedList::IntLinkedList()
{
	this->head = NULL;
}


IntLinkedList::~IntLinkedList(void)
{
	IntNode *temp;
	while (head) {
		temp = head;
		head = head->next;
		delete temp;
    }
	//This loop goes through each IntNode in the linkedlist and deletes it, freeing up memory.
}

void IntLinkedList::insert(int number)
{
	IntNode *newNode = new IntNode(number);
    newNode->next = this->head;
    head = newNode;
}

void IntLinkedList::displayList()
{
	IntNode *temp = head; //Start off at the start of the LinkedList, which is 'head'.

    while(temp!=NULL) //Do this loop until the list ends ('NULL'). 
    {
        cout<<temp->data<<endl; //Print the data (int) in the IntNode
        temp=temp->next; //Follow onto the 'next' IntNode in the LinkedList.
    } 
	cout<<endl;
}

void IntLinkedList::deleteMostRecent()
{
	IntNode *temp = this->head;
    head = head->next; //Set the beginning of the LinkedList to the next Node in the list
    delete temp; 
	
	//Delete the head. If you're wondering why we're deleting the head, it's because the 
	//head is where the most recently added IntNode is. So if you add '4' then '5' then '8' , the head
	//will be '8' , then the head will point to '5' and that will point to '4'.
}

void IntLinkedList::deleteInt(int pos)
{
	IntNode *current = head;
    IntNode *previous = current;

    if(current == NULL)
    {
        cout<<"Error , can not delete."<<endl;
    }

    bool cont = true;
    int currentNumber = 0; //The counter to keep track
    do
    {
        if(currentNumber == pos) // If the counter reaches the position.
        {
            previous->next = current->next;
            delete current;
            cont = false; // Delete the node and stop the loop
        }else
        {
            previous = current; //Set the previous node to the cuurent
            current = current->next;
            currentNumber++; //Increment the counter.
        }
    }while(cont == true);
}
